package com.zytlifeservice.service;

import com.zytlifeservice.constant.VerifyConstant;
import com.zytlifeservice.domain.User;
import com.zytlifeservice.domain.Verify;
import com.zytlifeservice.exception.UserException;
import com.zytlifeservice.repository.UserRepository;
import com.zytlifeservice.repository.VerifyRepository;
import com.zytlifeservice.util.TextUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created by MJS on 2017/4/28.
 */
@Service
public class VerifyService {

    private static final Logger logger = LoggerFactory.getLogger(VerifyService.class);

    @Autowired
    VerifyRepository verifyRepository;
    @Autowired
    UserRepository userRepository;
    //每次促发操作时删掉之前的验证码吧。
    @Autowired
    VerifyManager manager;

    public void send(String mobile, int type) {
        User user = userRepository.findByMobile(mobile);
        //这里涉及到如果是已经注册的话，则不发送验证码了。这个还是要区分才行。
        if (type == VerifyConstant.TYPE_REGISTER) {
            //注册
            //存在的话则提示已经注册，提示登陆，否者的话执行注册流程
            if (user != null) {
                throw new UserException("用户已经注册，请登陆", 103);
            }
        }
        manager.sendVerify(mobile);
    }


    /*
    注册时检验二维码
     */
    public void checkVerifyForRegister(String mobile, String verify) {
        if (TextUtil.isEmpty(verify)) {
            throw new UserException("验证码不能为空", 104);
        }
        List<Verify> verifyList = verifyRepository.findByMobileOrderBySendTimeDesc(mobile);
        Verify verifyRepositoryByMobile = verifyList.get(0);

        logger.info("verifyRepositoryByMobile={}", verifyRepositoryByMobile);
        if (verifyRepositoryByMobile.getStatus() == VerifyConstant.STATUS_ACTIVE || !verify.equals(verifyRepositoryByMobile.getVerifyCode())) {
            throw new UserException("验证码出错", 105); //加上当前验证码未被激活。
        }

        //下面的2个操作都需要更新验证码的状态
        verifyRepositoryByMobile.setStatus(VerifyConstant.STATUS_ACTIVE);
        verifyRepository.save(verifyRepositoryByMobile);
        //加上有效时间的检测。 和当前的验证码有10分钟的间隔。而重新请求验证码之后，则需刷新该验证码，并且未被激活。
        long curTime = new Date().getTime();

        long requestTime = verifyRepositoryByMobile.getSendTime().getTime();

        if (curTime - requestTime >= 10 * 60 * 1000) {
            throw new UserException("校验码过期", 103);
        }
    }
}
